import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    private String from;
    private String to;
    private String message;

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    //这个对象在多个方法中都要使用
    private ObjectMapper objectMapper=new ObjectMapper();
    private List<Message> messageList=new ArrayList<>();
    //负责让页面获取到数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //只需要一行代码，把messageList转成json字符串，并返回页面
        resp.getWriter().write(objectMapper.writeValueAsString(messageList));
    }
    //提交数据
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取到body中的数据并解析
        Message message=objectMapper.readValue(req.getInputStream(),Message.class);
        //把这个message保存一下
        messageList.add(message);
        resp.setStatus(200);
        System.out.println("提交成功");
    }
}
